package com.buu.app.controller;

import com.alibaba.fastjson.JSON;
import com.buu.common.annotation.Log;
import com.buu.common.controller.BaseController;
import com.buu.common.utils.MD5Utils;
import com.buu.common.utils.PageUtils;
import com.buu.common.utils.Query;
import com.buu.common.utils.R;
import com.buu.education.domain.EducationCommentDO;
import com.buu.education.domain.EducationEvaluateDO;
import com.buu.education.service.EducationCommentService;
import com.buu.education.service.EvaluateService;
import com.buu.evaluate.domain.EvaluateInfoDO;
import com.buu.evaluate.service.EvaluateInfoService;
import com.buu.manager.domain.EduDO;
import com.buu.manager.domain.StudyResourceDO;
import com.buu.manager.service.EduService;
import com.buu.manager.service.StudyResourceService;
import com.buu.system.domain.SysUserDO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Api
@RequestMapping("/app")
@Controller
public class AppController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private EduService eduService;

    @Autowired
    private StudyResourceService studyResourceService;
    @Autowired
    private EvaluateInfoService evaluateInfoService;

    @Autowired
    private EvaluateService evaluateService;

    @Autowired
    private EducationCommentService educationCommentService;

    @ApiOperation("手机客户端登录")
    @Log("手机客户端登录")
    @PostMapping("/login")
    @ResponseBody
    R ajaxLogin(String username, String password) {
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            //获取当前登录用户
            SysUserDO sysUserDO = (SysUserDO) subject.getPrincipal();
            //根据用户获取身份
            EduDO eduDO = eduService.getUserBySysUserId(sysUserDO.getUserId());
            return R.ok(eduDO);
        } catch (AuthenticationException e) {
            return R.error("用户或密码错误");
        }
    }

    /**
     * 获取学习资源
     * @param params
     * @return
     */
    @GetMapping("/study/list")
    @ResponseBody
    R list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        List<StudyResourceDO> eduList = studyResourceService.list(query);
        int total = studyResourceService.count(query);
        PageUtils pageUtil = new PageUtils(eduList, total);
        return R.ok(pageUtil);
    }

    /**
     * 根据年级获取教师信息
     * @param params
     * @return
     */
    @ApiOperation("根据年级获取教师信息")
    @GetMapping("/listTea")
    @ResponseBody
    R listTea(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        List<EduDO> eduList = eduService.list(query);
        int total = eduService.count(query);
        PageUtils pageUtil = new PageUtils(eduList, total);
        return R.ok(pageUtil);
    }

    /**
     * 根据教师获取所教年级的学生信息
     * @param params
     * @return
     */
    @ApiOperation("根据教师获取所教年级的学生信息")
    @GetMapping("/listStu")
    @ResponseBody
    R listStu(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        params.put("type", "2");
        Query query = new Query(params);
        List<EduDO> eduList = eduService.list(query);
        int total = eduService.count(query);
        PageUtils pageUtil = new PageUtils(eduList, total);
        return R.ok(pageUtil);

    }

    /**
     * 获取评价单
     * @return
     */
    @ApiOperation("获取教师评价单")
    @GetMapping("/viewlist")
    @ResponseBody
    R viewList(@RequestParam String type) {
        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        // 查询列表数据
        List<EvaluateInfoDO> eduList = evaluateInfoService.list(params);
        return R.ok(eduList);
    }

    /**
     * 获取学生评价结果
     * @param params
     * @return
     */
    @GetMapping("/list_stu_eva")
    @ResponseBody
    R listStuEva(@RequestParam Map<String, Object> params) {
        //获取id
        Long id = Long.valueOf(params.get("id").toString());
        //根据id获取身份
        EduDO eduDO = eduService.get(id);
        if(eduDO != null){
            List<EducationEvaluateDO> edus = null;
            int total = 0;
            // 查询列表数据
            //如果是学生，查询本人评价结果
            if("2".equals(eduDO.getType())){
                params.put("userId", eduDO.getSysUserId());
                edus = evaluateService.getEduEvaBySudentId(params);
                total = evaluateService.getEduEvaBySudentIdCount(params);
            } else if("1".equals(eduDO.getType())){
                //如果是老师，查看本人所在班级的所有学生的评价
                params.put("unit", eduDO.getUnit());
                edus = evaluateService.getEduEvaByUnit(params);
                total = evaluateService.getEduEvaByUnitCount(params);
            }else if("0".equals(eduDO.getType())){
                edus = evaluateService.getEduEvaByUnit(params);
                total = evaluateService.getEduEvaByUnitCount(params);
            }

            return R.ok(edus);
        }
        return null;
    }

    /**
     * 获取教师评价结果
     * @param params
     * @return
     */
    @GetMapping("/list_tea_eva")
    @ResponseBody
    R listTeaEva(@RequestParam Map<String, Object> params) {
        //获取id
        Long id = Long.valueOf(params.get("id").toString());
        //根据用户获取身份
        EduDO eduDO = eduService.get(id);
        if(eduDO != null){
            // 查询列表数据
            List<EducationEvaluateDO> edus = null;
            int total = 0;
            //如果是教师用户登录，则只能查看自己的评价结果
            if("1".equals(eduDO.getType())){
                params.put("eduUserId", eduDO.getSysUserId());
                edus = evaluateService.getEduEvaByUnit(params);
                evaluateService.getEduEvaByUnitCount(params);
            }else if("2".equals(eduDO.getType())){
                //如果是学生用户，则只查询自己评价的教师
                params.put("evaUserId", eduDO.getId());
                edus = evaluateService.getEduEvaByEvaSudentId(params);
                evaluateService.getEduEvaByEvaSudentId(params);
            }else if("0".equals(eduDO.getType())){
                //如果是督导用户，查看所有教师评价
                edus = evaluateService.getEduEvaByUnit(params);
                evaluateService.getEduEvaByUnitCount(params);
            }

            return R.ok(edus);
        }
        return null;
    }

    /**
     * 保存评价信息
     * @param params
     * @return
     */
    @ResponseBody
    @PostMapping("/save")
    R save(@RequestParam Map<String, Object> params) {
        List<Map> list = JSON.parseArray(String.valueOf(params.get("arrayObj")), Map.class);
        //选项
        List<String> choose = new ArrayList<>();
        //分数
        List<String> goals = new ArrayList<>();
        int goal = 0;
        for(Map map : list){
            //获取选项
            choose.add(String.valueOf((Integer) map.get("index")));
            //获取得分
            String goalsStr =  String.valueOf(map.get("value"));
            goals.add(goalsStr);
            goal = goal + Integer.parseInt(goalsStr);
        }
        //用户id
        String userId = (String) params.get("id");
        //对象类型，1-教师，2-学生
        String type = (String) params.get("type");
        //对象名称
        String name = (String) params.get("name");
        //评语
        String remark = (String) params.get("mark");
        EducationEvaluateDO educationEvaluateDO = new EducationEvaluateDO();
        educationEvaluateDO.setUserId(userId);
        educationEvaluateDO.setType(type);
        educationEvaluateDO.setGoal(String.valueOf(goal));
        educationEvaluateDO.setChoose(String.join(",", choose));
        educationEvaluateDO.setGoals(String.join(",", goals));
        educationEvaluateDO.setRemark(remark);
        educationEvaluateDO.setName(name);
        //获取当前登录用户
        Long currentId = Long.valueOf(params.get("currentId").toString());
        EduDO eduDO = eduService.get(currentId);
        educationEvaluateDO.setEvaUserId(eduDO.getId());
        educationEvaluateDO.setEvaName(eduDO.getName());

        int insertResult = evaluateService.save(educationEvaluateDO);
        if(insertResult > 0){
            return R.ok();
        }

        return R.error();
    }


    @ApiOperation("获取指定老师的评价平均分")
    @GetMapping("/getEvaByUserId")
    @ResponseBody
    R getEvaByUserId(Long userId) {
        Map<String,Object> param = new HashMap<>();
        param.put("userId", userId);
        List<EducationEvaluateDO> eduList = evaluateService.statisticslist(param);
        return R.ok(eduList);
    }

    @ApiOperation("获取评分区间")
    @GetMapping("/comment_list")
    @ResponseBody
    R commentList() {
        List<EducationCommentDO> eduList = educationCommentService.list();
        return R.ok(eduList);
    }
}
